﻿using System.Threading.Tasks;
using SmartCity.Shared;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace CommonManagement
{
    /// <summary>
    /// 用户应用服务类
    /// </summary>
    public class UserAppService : ApplicationService, IUserAppService
    {
        private readonly IAuthManager _authManager;
        private readonly IRepository<User, int> _userRepository;

        public UserAppService(
            IAuthManager authManager,
            IRepository<User, int> userRepository)
        {
            _authManager = authManager;
            _userRepository = userRepository;
        }

        // 获取信息
        public async Task<UserGetInfoResponse> GetInfoAsync()
        {
            var id = _authManager.GetUserId();
            var user = await _userRepository.SingleOrDefaultAsync(m => m.Id == id);
            if (user == null)
                return UserGetInfoResponse.NotFound(id);
            var dto = ObjectMapper.Map<User, UserDto>(user);
            return UserGetInfoResponse.Successful(dto);
        }

        // 更新
        public async Task<UserUpdateResponse> UpdateAsync(UserUpdateDto input)
        {
            var id = _authManager.GetUserId();
            var user = await _userRepository.SingleOrDefaultAsync(m => m.Id == id);
            if (user == null)
                return UserUpdateResponse.NotFound(id);
            user.SetUser(
                input.Avatar,
                input.NickName,
                input.Sex,
                input.Phonenumber,
                input.Email,
                input.IdCard);
            return UserUpdateResponse.Successful();
        }

        // 重置密码
        public async Task<UserResetPwdResponse> ResetPwdAsync(UserResetPwdDto input)
        {
            var id = _authManager.GetUserId();
            var user = await _userRepository.SingleOrDefaultAsync(m => m.Id == id);
            if (user == null)
                return UserResetPwdResponse.NotFound(id);
            if (!user.Password.Equals(input.OldPassword))
                return UserResetPwdResponse.OldPasswordMismatch();
            user.SetPassword(input.NewPassword);
            return UserResetPwdResponse.Successful();
        }
    }
}